<script setup>
import { register_article_list, submitReject, editSubmitReject, register_batch_list, stock_withdrawApply } from '@/api/reject/stockList.js';
import { Download } from '@element-plus/icons-vue';
import { ElMessageBox, ElMessage } from 'element-plus'

const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
});
const { proxy } = getCurrentInstance();

const articleBatch = ref([])
const loading = ref(false);
const totalV = ref(0);
const articleList = ref([]);
const queryFormRef = ref();
const ids = ref([]);
const items = ref([]);
const dialog = ref({
    title: "",
    visible: false,
});
const unShowColumn = ref(false)
const multipleTableRef = ref()//清多选

/** 查询 */
function handleQuery() {
    loading.value = true;
    register_article_list(queryParams.value)
        .then(({ rows, total }) => {
            articleList.value = rows;
            totalV.value = total;
        })
        .finally(() => {
            loading.value = false;
        });
}

// 获取批次列表
function getBatchList() {
    register_batch_list().then((res) => {
        articleBatch.value = res.data.map(item => ({ label: item.name, value: item.id }));
    })
}
/** 重置查询 */
function resetQuery() {
    queryFormRef.value.resetFields();
    queryParams.pageNum = 1;
    handleQuery();
}


/** 行checkbox 选中事件 */
function handleSelectionChange(selection) {
    ids.value = selection.map((item) => ({ batchId: item.batchId, productsId: item.productsId, objectName: item.objectName }));
}

// const toggleSelection = (rows) => {
//   if (rows) {
//     rows.forEach((row) => {
//       // TODO: improvement typing when refactor table
//       // eslint-disable-next-line @typescript-eslint/ban-ts-comment
//       // @ts-expect-error
//       multipleTableRef.value!.toggleRowSelection(row, undefined)
//     })
//   } else {
//     multipleTableRef.value!.clearSelection()
//   }
// }

/** 打开表单弹窗 */
function openDialog(row) {

    dialog.value.visible = true;



    // if (row.applyWasteId === null) {
    //     dialog.value.title = "申请报废处理";

    //     // if (ids.value.length === 0) {
    //     let itemTemp = {
    //         id: row.id,
    //         batchId: row.batchId,
    //         productsId: row.productsId,
    //         objectName: row.objectName,
    //         flag: 1,
    //         applyWasteId: row.applyWasteId
    //     };
    //     items.value.push(itemTemp)
    //     // } else { 
    //     //     items.value = ids.map(item => ({
    //     //         id:item.id,
    //     //         batchId: item.batchId, 
    //     //         productsId: item.productsId,
    //     //         objectName: item.objectName
    //     //     }));
    //     // }
    // }
    // if (row.applyWasteId !== null) {
    dialog.value.title = "修改报废申请";

    let itemTemp = {
        id: row.id,
        batchId: row.batchId,
        productsId: row.productsId,
        objectName: row.objectName,
        flag: 1,
        objectAmount: Number(row.objectAmount),
        // applyWasteId: row.applyWasteId
    };
    items.value.push(itemTemp)



    // }
}

/** 保存提交 */
function handleSubmit() {

    loading.value = true;

    // ElMessageBox.confirm("确认提交报废么？", "警告", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    // }).then(
    //     function () {
    //         return submitReject(items.value[0])
    //     }
    // )

    // if(items.value[0].applyWasteId===null){

    submitReject(items.value[0]).then(() => {
        ElMessage.success("提交成功");
        // dialog.value.visible = false;
        closeDialog();
        resetQuery();
    })
        .finally(() => (loading.value = false));
    // }

    // if(items.value[0].applyWasteId!==null){
    //     editSubmitReject(items.value[0]).then(() => {
    //         ElMessage.success("提交成功");
    //         // dialog.value.visible = false;
    //         closeDialog();
    //         resetQuery();
    //     })
    //     .finally(() => (loading.value = false));}

}

/** 关闭表单弹窗 */
function closeDialog() {
    dialog.value.visible = false;
    multipleTableRef.value.clearSelection()
    // resetForm();
    ids.value = []
    items.value = []
}

/** 打开表单弹窗 */
function checkSubmit(row) {

    ElMessageBox.confirm('确定撤回吗?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(
            async () => {
                // 请求接口 删除数据
                let r = await stock_withdrawApply(row.id)
                if (r.code === 200) {
                    ElMessage({ type: 'success', message: '撤回成功' })
                } else {
                    ElMessage({ type: 'info', message: r.data })
                }
            }
        ).catch(() => {
            ElMessage({
                type: 'info', message: '撤回失败'
            })
        }).finally(() => {
            handleQuery()
        })
}

/** 导出按钮操作 */
const exportExcelFn = async () => {

    proxy.download("/applyWaste/export", {
        ...queryParams.value,
    }, `apply_${new Date().getTime()}.xlsx`);

}

const articleStatus = ref([{ value: 1, label: '待审核' }, { value: 0, label: '已通过' }, { value: 2, label: '已驳回' }])

// 计算属性，用于获取 status 对应的标签类型（可选，取决于你是否需要为标签设置不同的类型）  
const getStatusType = computed(() => {
    const typeMap = {
        1: 'info', // 例如：待审核为信息类型  
        0: 'success', // 已通过为成功类型  
        2: 'warning', // 已驳回为警告类型  
    };
    return (status) => typeMap[status] || 'default'; // 默认类型  
});

// 方法，用于根据 status 获取对应的 label  
function getStatusLabel(status) {
    return articleStatus.value.find((item) => item.value === status)?.label || '未操作';
}

onMounted(() => {
    handleQuery();
    getBatchList();
});
</script>

<template>
      <el-card class="page-container">

    <!-- <div class="app-container">
        <div class="search-container">
            <el-card shadow="hover" class="elCard"> -->
                <el-form ref="queryFormRef" :model="queryParams" :inline="true">

                    <el-form-item prop="objectName" label="用品名称">
                        <el-input v-model="queryParams.objectName" placeholder="用品名称" clearable
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="批次" prop="batchId">
                        <el-select v-model="queryParams.batchId">
                            <el-option v-for="(item, index) in articleBatch" :index="item.value" :key="index"
                                :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="flag" label="报废处理状态">
                        <el-select v-model="queryParams.flag">
                            <el-option v-for="(item, index) in articleStatus" :index="item.value" :key="index"
                                :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleQuery"><el-icon>
                                <Search />
                            </el-icon>搜索</el-button>
                        <el-button @click="resetQuery"><el-icon>
                                <Refresh />
                            </el-icon>重置</el-button>
                    </el-form-item>
                </el-form>
            <!-- </el-card>
        </div> -->

        <!-- <el-card shadow="never" class="table-container"> -->
        <div class="mb8">

            <!-- <template #header>
                <el-button type="success" :disabled="ids.length === 0" @click="openDialog()"><el-icon><DeleteFilled /></el-icon>批量报废处理</el-button>
            </template> -->
            <!-- <template #header> -->
                <el-button type="primary" plain icon="Plus" @click="exportExcelFn"> 导出</el-button>
            <!-- </template> -->
                </div>
            <el-table v-loading="loading" :data="articleList" highlight-current-row border stripe height="520"
                style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column type="index" label="序号" align="center" width="55">
                    <template #default="scope">
                        <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="记录id" prop="id"  v-if="unShowColumn" align="center"/>
                <el-table-column label="用品id" prop="productsId" v-if="unShowColumn" align="center"/>
                <el-table-column label="所属批次" prop="batchId"   align="center">
                    <template #default="scope">
                        <template v-for="item, index in articleBatch">
                            <span v-if="item.value == scope.row.batchId">
                                {{ item.label }}
                            </span>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="申请人" prop="applicant"  align="center"/>
                <el-table-column label="用品名称" prop="objectName"   align="center"/>
                <!-- <el-table-column label="所属批次" prop="batchName" min-width="100" /> -->
                <el-table-column label="库存数量" prop="productsNum" align="center"/>
                <el-table-column label="待报废总数" prop="productsUnqualified" align="center"/>
               <el-table-column label="申请数量" prop="objectAmount" align="center"/>
              <el-table-column label="处理状态"
                    prop="flag" align="center">
                    <template #default="scope">

                        <el-tag :type="getStatusType(scope.row.flag)">
                            {{ getStatusLabel(scope.row.flag) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="拒绝原因" prop="rejectAdvice" width="150" show-overflow-tooltip align="center">
                    <template #default="scope">
                        <span v-if="scope.row.flag === 2">
                            {{ scope.row.rejectAdvice }}
                        </span>
                        <span v-if="scope.row.flag !== 2">
                            -
                        </span>
                    </template>
                </el-table-column>

                <el-table-column fixed="right" label="操作" width="220" align="center">
                    <template #default="scope">
                        <!-- <el-button v-if="scope.row.applyWasteId === null" type="primary" size="small" link
                            @click="openDialog(scope.row)"><el-icon>
                                <DeleteFilled />
                            </el-icon>申请报废处理
                        </el-button> -->
                        <el-button v-if="scope.row.flag !== 1" type="primary" size="small" link>申请已处理，无法操作
                        </el-button>
                        <el-button v-if="scope.row.flag === 1" type="primary" size="small" link
                            @click="openDialog(scope.row)"><el-icon>
                                <Edit />
                            </el-icon>修改报废申请
                        </el-button>
                        <el-button v-if="scope.row.flag === 1" type="primary" size="small" link
                            @click="checkSubmit(scope.row)"><el-icon>
                                <RefreshLeft />
                            </el-icon>撤回
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                :page-sizes="[10, 20, 30, 40]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="totalV" @size-change="handleQuery" @current-change="handleQuery" style="margin-top: 20px; justify-content: flex-end"/>
        <!-- </el-card> -->

        <!-- 表单弹窗 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="700px" @close="closeDialog" draggable>
            <div>
                <div v-for="(item, index) in items" :key="item.id" class="item-container">
                    <!-- 展示name -->
                    <span class="item-name">{{ item.objectName }}的报废数量:</span>
                    <!-- 输入框，用于输入数量 -->
                    <!-- <input type="number" class="item-input" v-model="item.objectAmount" >   -->
                    <el-input-number v-model="item.objectAmount" :min="1" :style="{ width: '200px' }"
                        placeholder="输入报废数量" />
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmit">确 定</el-button>
                    <el-button @click="closeDialog">取 消</el-button>
                </div>
            </template>
        </el-dialog>

    <!-- </div> -->
    </el-card>
</template>

<style scoped>
.elCard {
    margin-bottom: 10px;
}

.el-card {
    --el-card-padding: 12px;
}

.el-pagination {
    margin-top: 10px;
    margin-left: 10px;
}

.item-container {
    /* 根据需要设置容器的宽度，或者让它自适应 */
    /* width: 100%; */
    display: flex;
    /* 使用flex布局可以更容易地对齐子元素 */
    align-items: center;
    /* 垂直对齐子元素 */
}

.item-name {
    display: inline-block;
    /* 确保span元素在同一行内 */
    width: 200px;
    /* 设置span的宽度 */
    text-align: end;
    margin-right: 10px;
    font-size: 16px;
    line-height: 40px;

    /* 其他样式，如字体大小、颜色等 */
}

.item-input {
    display: inline-block;
    /* 确保input元素在同一行内 */
    width: 300px;
    /* 设置input的宽度 */
    /* 其他样式，如边框、内边距等 */
}
</style>